package com.hmall.item.service.impl;

import cn.hutool.db.Page;
import cn.hutool.db.sql.Direction;
import cn.hutool.db.sql.Order;
import com.hmall.common.domain.PageDTO;
import com.hmall.common.exception.BizIllegalException;
import com.hmall.item.domain.dto.ItemDocDTO;
import com.hmall.item.domain.query.ItemPageQuery;
import com.hmall.item.es.EsQueryResult;
import com.hmall.item.es.EsResultOperator;
import com.hmall.item.es.EsSearchCommonService;
import com.hmall.item.service.ISearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.AbstractQueryBuilder;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.hmall.common.constants.MqConstants.*;

/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2022/4/19 9:25
 */
@Service
@Slf4j
@RefreshScope
public class SearchCommonService implements ISearchService {
    @Value("${hm.es.aggregationCount}")
    private Integer aggregationCount;
    @Autowired
    private EsSearchCommonService esSearchCommonService;

    /**
     * 1、商品搜索
     * @param params 搜索条件参数
     * @return
     */
    @Override
    public PageDTO<ItemDocDTO> search(ItemPageQuery params) {
        try {
            // 1.准备请求参数
            // 1.1、构建查询条件
            QueryBuilder queryBuilder = buildBasicQuery(params);

            // 1.2、构建分页和排序参数
            Page page = new Page(params.getPageNo(), params.getPageSize());
            page.addOrder(new Order(params.getSortBy(), params.getIsAsc() ? Direction.ASC : Direction.DESC));

            //1.3、构建高亮 Builder
            HighlightBuilder highlight = new HighlightBuilder().field("name").requireFieldMatch(false);

            //2、执行查询，解析结果
            EsQueryResult esQueryResult = esSearchCommonService.excuteQuery("items", ItemDocDTO.class,
                    queryBuilder, EsResultOperator.builder().page(page).highLight(highlight).build());

            List<ItemDocDTO> results = esQueryResult.getResultList();
            Long total = esQueryResult.getTotal();
            Long totalPage = total / params.getPageSize() == 0 ? total / params.getPageSize() : total / params.getPageSize() + 1;
            return new PageDTO<>(total, totalPage, results);

        } catch (Exception e) {
            log.error("搜索数据失败", e);
            throw new BizIllegalException("搜索数据失败");
        }
    }

    /**
     * 构建查询条件
     */
    private AbstractQueryBuilder buildBasicQuery(ItemPageQuery params) {
        // 1.准备Boolean查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // 1.1.关键字搜索，match查询，放到must中
        String key = params.getKey();
        if (StringUtils.isNotBlank(key)) {
            // 不为空，根据关键字查询
            boolQuery.must(QueryBuilders.matchQuery("name", key));
        } else {
            // 为空，查询所有
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        // 1.2.品牌
        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand", brand));
        }
        // 1.3.分类
        String category = params.getCategory();
        if (StringUtils.isNotBlank(category)) {
            boolQuery.filter(QueryBuilders.termQuery("category", category));
        }
        // 1.4.价格范围
        Integer minPrice = params.getMinPrice();
        Integer maxPrice = params.getMaxPrice();
        if (minPrice != null && maxPrice != null) {
            maxPrice = maxPrice == 0 ? Integer.MAX_VALUE : maxPrice;
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice * 100).lte(maxPrice * 100));
        }

        // 2.算分函数查询
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                boolQuery, // 原始查询，boolQuery
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{ // function数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true), // 过滤条件
                                ScoreFunctionBuilders.weightFactorFunction(100) // 算分函数
                        )
                }
        );
        // 3.返回查询条件
        return functionScoreQuery;
    }

    /**
     * 2、商品聚合查询（聚合查询符合条件的所有 【品牌】 和 【分类】）
     * @param params
     * @return
     */
    @Override
    public Map<String, List<String>> getFilters(ItemPageQuery params) {
        try {
            // 1、构建查询条件
            QueryBuilder queryBuilder = buildBasicQuery(params);
            // 2、构建桶聚合
            TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brandAgg").field("brand").size(aggregationCount);
            TermsAggregationBuilder categoryAgg = AggregationBuilders.terms("categoryAgg").field("category").size(aggregationCount);

            Aggregations aggregations = this.esSearchCommonService.getAggregations("items", queryBuilder, brandAgg, categoryAgg);

            Map<String, List<String>> filters = new HashMap<>(2);
            // 4.1.解析品牌
            List<String> brandList = this.esSearchCommonService.getAggResultForAggName(aggregations, "brandAgg");
            filters.put("brand", brandList);
            // 4.1.解析品牌
            List<String> categoryList = this.esSearchCommonService.getAggResultForAggName(aggregations, "categoryAgg");
            filters.put("category", categoryList);
            return filters;

        } catch (Exception e) {
            log.error("聚合查询失败", e);
            throw new BizIllegalException("聚合查询失败");
        }
    }

}
